﻿namespace CommonUtils
{
    public static class PathConfig
    {
        /// <summary>
        /// 工作目录 默认为可运行程序/服务目录 可通过SetWorkFolder配置
        /// 相对路径在发布到服务、IIS时会出错，所以此处使用绝对路径
        /// </summary>
        public static string WorkFolder { get; private set; } = PathUtil.AppBase;

        public const string ConfigFolderName = "configs";
        //配置文件夹 相对路径在发布到服务、IIS时会出错，所以此处使用绝对路径
        public static string ConfigFolder { get; private set; }

        //默认配置文件名
        public const string DefaultConfigFileName = "settings.json";

        //分支根目录名
        public const string SubRootIdentifier = "sub";
        //分支配置文件夹
        public static string SubConfigFolder { get; private set; }

        //默认分支（没有分支）标识 网页拿不到值会传入"undefined",所以用这个
        public const string NoSubIdentifier = "undefined";

        //语言文件夹
        public static string LanguageFolder { get; private set; }

        //默认数据库路径
        public static string DefaultSqlitePath { get; private set; }
        //开销文件夹
        public static string AppDataFolder { get; private set; }

        //日志文件夹
        public static string LogFolder { get; private set; }
        //分支日志文件夹
        public static string SubLogFolder { get; private set; }

        //记录异常文件夹
        public static string ErrorFolder { get; private set; }
        //记录分支异常文件夹
        public static string SubErrorFolder { get; private set; }

        private static void SetPaths()
        {
            ConfigFolder = WorkFolder.Combine(ConfigFolderName);
            SubConfigFolder = ConfigFolder.Combine(SubRootIdentifier);

            LanguageFolder = ConfigFolder.Combine("languages");

            AppDataFolder = WorkFolder.Combine("App_Data");
            DefaultSqlitePath = AppDataFolder.Combine("sqlite.db");

            LogFolder = AppDataFolder.Combine("log");
            SubLogFolder = LogFolder.Combine(SubRootIdentifier);

            ErrorFolder = AppDataFolder.Combine("error");
            SubErrorFolder = ErrorFolder.Combine(SubRootIdentifier);
        }

        static PathConfig()
        {
            SetPaths();
        }

        /// <summary>
        /// 设置根目录 请使用绝对路径 很多服务类型的程序不设置的话，日志文件就不知道去哪了
        /// </summary>
        public static void SetWorkFolder(string folder)
        {
            WorkFolder = folder;
            SetPaths();
        }

        /// <summary>
        /// 获取开销路径
        /// </summary>
        public static string GetRuntimesPath(params string[] rights)
        => AppDataFolder.Combine(rights);

        /// <summary>
        /// 获取临时路径
        /// </summary>
        public static string GetTemp(string nameOrExtension)
        {
            var longTimestamp = TimeUtil.GetLongStamp();
            if (nameOrExtension.StartsWith('.'))
                nameOrExtension = longTimestamp + nameOrExtension;
            return GetRuntimesPath("temp", nameOrExtension);
        }
    }
}
